<?php

/*
	Class: Cts_Acl

	About: Author
		Jaybill McCarthy

	About: License
		<http://communit.as/docs/license>

	About: See Also
		Zend_Acl
*/
class Cts_Acl extends Zend_Acl {

	/* Group: Constructors */

	/*
		Constructor: __construct

		Arguments:
			auth - A Zend_Auth object.
	*/
	public function __construct(Zend_Auth $auth) {
       	// we need to do this recursively because of role inheritance
       	$this->addRoles();
       	$resources = new RolesResources();
       	$rsResources = $resources->fetchAll();

       	foreach ($rsResources as $resource) {
       		$fullname = $resource->module . "-" . $resource->controller . "-" . $resource->action;

			if (!$this->has($fullname)) {
				$this->add(new Zend_Acl_Resource($fullname));
			}
			$this->allow($resource->role_id, $fullname);
       	}
    }

	/* Group: Instance Methods */

	/*
		Function: addRoles

		Arguments:
			parent_role (optional) - TBD
	*/
    function addRoles($parent_role = null) {
    	$roles_table = new Roles();
    	// we start this recursive funtion by looking for roles with no parent.

    	if (is_null($parent_role)) {
    		$where = 'inherits_id is null';
    	} else {
    		$where = 'inherits_id=' . $parent_role;
    	}
    	$roles = $roles_table->fetchAll($where);
    	foreach ($roles as $role) {
    		// Add the role and specifiy that the parent. On the first pass, this is null.

    		$this->addRole(new Zend_Acl_Role($role->id), $parent_role);

    		// see if this is a "special" role
    		if ($role->isadmin) {
				Zend_Registry::set('admin_role', $role->id);
			}

			if ($role->isguest) {
				Zend_Registry::set('guest_role', $role->id);
			}

			if ($role->isdefault) {
				Zend_Registry::set('default_role', $role->id);
			}
			// call this function with this role id as parent id
    		$this->addRoles($role->id);
    	}
    }
}
